const fs = require('fs');
const pdf = require('pdf-parse');

var dir = "./0925"

async function read() {
    var ok = {}
    var ex = []
    var data = fs.readdirSync(dir)
    var total = 0
    for (var i = 0; i < data.length; i++) {
        var file = data[i]
        if (!file.endsWith(".pdf")) continue;
        let dataBuffer = fs.readFileSync(dir + '/' + file);

        var info = await pdf(dataBuffer);
        var arr = /\n(?:¥\s?)(\d+\.\d{2})(?!¥)/g.exec(info.text)
        if (arr && arr.length > 1) {
            var r = arr[1]
            total += parseFloat(r)
            // console.log(file, '\t\t\t', r);
            ok[file] = r
        }
        else {
            arr = info.text.match(/\d+\.\d{2}/g)
            if (arr && arr.length == 2) {
                var r = parseFloat(arr[0]) + parseFloat(arr[1])
                total += r
                ok[file] = r
            }
            else {
                // console.log(file, info.text);
                // console.log(file);
                ex.push(file)
            }
        }
    }
    if (ex.length > 0) {
        console.log('异常文件：\r\n' + ex.join('\r\n'));
        console.log('\r\n\r\n');
    }

    var max = Object.keys(ok).map(k => k.length).sort((a, b) => (a - b) > 0 ? -1 : 1)[0]
    var info = []
    var sl = 16
    for (var p in ok) {
        var cc = p.match(/([\u4E00-\u9FA5])/g)
        var s = cc ? cc.length : 0
        info.push(p + Array(max - p.length + sl - s).join(' ') + ok[p])
    }
    console.log('发票文件名' + Array(max - 5 + sl - 5).join(' ') + '金额');
    console.log(info.join('\r\n'));
    console.log('\r\ntotal:' + Array(max - 6 + sl).join(' ') + total);
}

read()